/*
# @Time    : 2019/6/25 11:19
# @Author  : Mickel Xiang
# @File    : etcd.go
# @Function: -----------
*/
package controllers

import (
	"net/http"
	"html/template"
	"github.com/coreos/etcd/clientv3"
	"fmt"
	"context"
	"time"
)
type (
	EtcdController struct {
		etcd *clientv3.Client
	}
)
func NewEtcdController(etcd *clientv3.Client) *EtcdController {
	return &EtcdController{etcd}
}
func (etcd *EtcdController) AddHandler(w http.ResponseWriter, r *http.Request) {

	v := r.URL.Query();
	key := v.Get("key")
	data := make(map[string]string)
	if key!=""{
		ctx, cancel := context.WithTimeout(context.Background(), time.Second)
		resp, err := etcd.etcd.Get(ctx, key)
		cancel()
		if err != nil {
			fmt.Println("get failed, err:", err)
			return
		}

		if resp.Count==1{
			for _, ev := range resp.Kvs {
				fmt.Printf("%s : %s\n", ev.Key, ev.Value)
				data[string(ev.Key)]=string(ev.Value)
			}
		}
	}else{
		data[""]=""
	}
	t,_:=template.ParseFiles("templates/add.html")
	t.Execute(w, data)
}

func (etcd *EtcdController) PutHandler(w http.ResponseWriter, r *http.Request){
	key:=r.PostFormValue("key")

	if key==""{
		w.Write([]byte("key is requred"))
		return
	}
	value:=r.PostFormValue("value")
	if value==""{
		w.Write([]byte("value is requred"))
		return
	}
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	_, err := etcd.etcd.Put(ctx, key, value)
	cancel()
	if err != nil {
		fmt.Println("put failed, err:", err)
		return
	}
	url := "/"
	http.Redirect(w,r, url, http.StatusFound)
}
func (etcd *EtcdController) DeleteHandler(w http.ResponseWriter, r *http.Request){
	v := r.URL.Query();
	key := v.Get("key")

	if key==""{
		w.Write([]byte("key is requred"))
		return
	}
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	_, err := etcd.etcd.Delete(ctx, key)
	cancel()
	if err != nil {
		fmt.Println("put failed, err:", err)
		return
	}
	url := "/"
	http.Redirect(w,r, url, http.StatusFound)
}
func (etcd *EtcdController)IndexHandler(w http.ResponseWriter, r *http.Request) {

	// 获取所有 key value
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	resp, err := etcd.etcd.Get(ctx, "/",clientv3.WithPrefix())
	cancel()
	if err != nil {
		fmt.Println("get failed, err:", err)
		return
	}
	//用于保存数据的map
	data := make(map[string]string)

	for _, ev := range resp.Kvs {
		//fmt.Printf("%s : %s\n", ev.Key, ev.Value)
		data[string(ev.Key)]=string(ev.Value)
	}
	t, _ := template.ParseFiles("templates/index.html")
	t.Execute(w, data)
}